<template>
  <view class="user-info-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-button" @tap="navigateBack">
        <uni-icons type="arrow-left" size="28" color="#000"></uni-icons>
      </view>
      <view class="nav-title">个人资料</view>
      <view class="nav-right">
        <uni-icons type="ellipsis" size="28" color="#000"></uni-icons>
      </view>
    </view>

    <!-- 个人资料列表 -->
    <view class="info-list">
      <!-- 头像 -->
      <view class="info-item" @tap="onChooseAvatar">
        <view class="info-label">头像</view>
        <view class="avatar-container">
          <image :src="state.model.avatarUrl || defaultAvatar" class="avatar"></image>
          <uni-icons type="right" size="22" color="#ccc"></uni-icons>
        </view>
      </view>

      <!-- 昵称 -->
      <view class="info-item" @tap="showNicknameDialog()">
        <view class="info-label">昵称</view>
        <view class="info-value-with-arrow">
          <text v-if="state.model.nickname">{{ state.model.nickname }}</text>
          <text v-else class="placeholder">请输入昵称</text>
          <uni-icons type="right" size="22" color="#ccc"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 底部保存按钮 -->
    <view class="footer">
      <button class="save-button" @tap="onSubmit">保存</button>
    </view>

    <!-- 隐藏的文件输入框 -->
    <input
        type="file"
        accept="image/*"
        style="display: none;"
        ref="fileInput"
        @change="handleFileSelect"
    />

    <!-- 编辑昵称弹窗 -->
    <su-popup
        v-model:show="showNicknamePopup"
        type="center"
        :is-mask-click="false"
        background-color="transparent"
        :round="0"
    >
      <view class="nickname-popup-content">
        <view class="popup-header">
          <view class="popup-title">编辑昵称</view>
          <uni-icons class="close-icon" type="closeempty" size="28" @tap="showNicknamePopup = false"></uni-icons>
        </view>
        <view class="input-container">
          <input
              v-model="nicknameInput"
              type="text"
              placeholder="请输入昵称"
              maxlength="15"
              class="nickname-input"
              @input="handleNicknameInput"
          />
          <view class="char-count">{{ nicknameInput.length }}/15</view>
        </view>
        <button
            class="save-nickname-button"
            @tap="saveNickname"
            :disabled="!nicknameInput || nicknameInput.length > 15"
        >
          保存
        </button>
      </view>
    </su-popup>

    <!-- 底部退出登录按钮 -->
    <view class="footer">
      <button class="logout-button" @tap="handleLogout">退出登录</button>
    </view>
  </view>
</template>

<script setup>
import {computed, onBeforeMount, reactive, ref} from "vue";
import sheep from "@/sheep";
import SuPopup from '@/sheep/ui/su-popup/su-popup.vue';

const state = reactive({
  model: {
    avatarUrl: "", // 初始化头像 URL
    nickname: "", // 初始化昵称
  },
  rules: {},
  thirdOauthInfo: null,
  uploading: false, // 上传状态标记
  uploadProgress: 0, // 上传进度
});

// 默认头像
const defaultAvatar = '';

// 文件输入框引用
const fileInput = ref(null);
const showNicknamePopup = ref(false);
const nicknameInput = ref('');

// 页面加载时获取用户信息
onBeforeMount(() => {
  // 从 store 中获取用户信息
  const currentUser = sheep.$store("user").userInfo;
  if (currentUser) {
    state.model.nickname = currentUser.nickname || "";
    state.model.avatarUrl = currentUser.avatar || "";
  }
});

// 返回上一页
function navigateBack() {
  sheep.$router.back();
}

// 触发文件选择
function onChooseAvatar() {
  if (typeof uni !== 'undefined') {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePath = res.tempFilePaths[0];
        // 上传图片
        uploadAvatar(tempFilePath);
      },
      fail: function (err) {
        console.error('选择图片失败:', err);
        sheep.$helper.toast('选择图片取消');
      }
    });
  } else if (fileInput.value && fileInput.value.click) {
    // 在H5环境中，仍然使用原来的方式
    fileInput.value.click();
  }
}

// 处理文件选择事件 (H5环境)
function handleFileSelect(event) {
  const file = event.target.files[0];
  if (file) {
    // 检查文件大小（限制5MB）
    if (file.size > 5 * 1024 * 1024) {
      sheep.$helper.toast('图片大小不能超过5MB');
      return;
    }

    // 检查文件类型
    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!validTypes.includes(file.type)) {
      sheep.$helper.toast('请选择有效的图片文件');
      return;
    }

    // 创建文件读取器
    const reader = new FileReader();
    reader.onload = function (e) {
      // 先显示本地预览
      state.model.avatarUrl = e.target.result;
      // 然后上传文件
      uploadAvatarFile(file);
    };
    reader.readAsDataURL(file);
  }
}

// 上传文件 (H5环境)
async function uploadAvatarFile(file) {
  try {
    state.uploading = true;
    // 调用上传API
    const jsonStr = await sheep.$api.app.upload(file);
    let result = JSON.parse(jsonStr);
    console.log(result);
    if (result.code === 200) {
      // 更新为服务器返回的图片URL
      state.model.avatarUrl = result.data || '';
      sheep.$helper.toast('头像上传成功');
      const currentUser = sheep.$store("user").userInfo;
      // 调用更新用户信息的接口
      await sheep.$api.user.updateUser({
        ...currentUser,
        avatar: state.model.avatarUrl,
      });
    } else {
      sheep.$helper.toast(result.msg || '头像上传失败');
    }
    state.uploading = false;
  } catch (error) {
    state.uploading = false;
    console.error('上传过程中出错:', error);
    sheep.$helper.toast('上传失败，请重试');
  }
}

// 上传图片 (小程序环境)
async function uploadAvatar(tempFilePath) {
  try {
    state.uploading = true;
    const jsonStr = await sheep.$api.app.upload(tempFilePath);
    let result = JSON.parse(jsonStr);
    console.log(result);
    // 移除这行提前设置uploading为false的代码
    if (result.code === 200) {
      // 更新为服务器返回的图片URL
      state.model.avatarUrl = result.data || '';
      sheep.$helper.toast('头像上传成功');
      const currentUser = sheep.$store("user").userInfo;
      // 调用更新用户信息的接口
      await sheep.$api.user.updateUser({
        ...currentUser,
        avatar: state.model.avatarUrl,
      });
    } else {
      sheep.$helper.toast(result.msg || '头像上传失败');
    }
    state.uploading = false; // 只在所有操作完成后才设置为false
  } catch (error) {
    state.uploading = false;
    console.error('上传失败:', error);
    sheep.$helper.toast('网络异常，请稍后重试');
  }
}

// 提交表单 - 更新用户信息
async function onSubmit() {
  // 表单验证
  if (!state.model.nickname) {
    sheep.$helper.toast('昵称不能为空');
    return;
  }

  if (state.model.nickname.length > 20) {
    sheep.$helper.toast('昵称不能超过20个字符');
    return;
  }

  try {
    // 防止重复提交
    if (state.uploading) {
      sheep.$helper.toast('头像上传中，请稍候再保存');
      return;
    }

    const currentUser = sheep.$store("user").userInfo;
    // 调用更新用户信息的接口
    const result = await sheep.$api.user.updateUser({
      ...currentUser,
      nickname: state.model.nickname,
      avatar: state.model.avatarUrl,
    });

    // 检查响应结果
    if (result.code === 200) {
      // 保存更新后的用户信息到 store
      sheep.$store("user-store").userInfo = {
        ...currentUser,
        nickname: state.model.nickname,
        avatar: state.model.avatarUrl,
      };

      // 提示成功并返回上一页
      sheep.$helper.toast('保存成功');
      setTimeout(() => {
        sheep.$router.back();
      }, 1500);
    } else {
      // 提示失败信息
      sheep.$helper.toast(result.msg || '保存失败，请重试');
    }
  } catch (error) {
    sheep.$helper.toast('网络异常，请稍后重试');
    console.error('更新用户信息失败:', error);
  }
}

// 处理昵称输入
function handleNicknameInput() {
  // 限制输入字数为15个字符
  if (nicknameInput.value.length > 15) {
    nicknameInput.value = nicknameInput.value.substring(0, 15);
  }
}

// 保存昵称
async function saveNickname() {
  // 表单验证
  if (!nicknameInput.value.trim()) {
    sheep.$helper.toast('昵称不能为空');
    return;
  }

  if (nicknameInput.value.length > 15) {
    sheep.$helper.toast('昵称不能超过15个字符');
    return;
  }

  try {
    // 关闭弹窗
    showNicknamePopup.value = false;

    // 更新本地状态
    state.model.nickname = nicknameInput.value.trim();

    const currentUser = sheep.$store("user").userInfo;
    // 调用更新用户信息的接口
    const result = await sheep.$api.user.updateUser({
      ...currentUser,
      nickname: state.model.nickname
    });

    // 检查响应结果
    if (result.code === 200) {
      // 保存更新后的用户信息到 store
      sheep.$store("user").userInfo = {
        ...currentUser,
        nickname: state.model.nickname
      };

      // 提示成功
      sheep.$helper.toast('昵称修改成功');
    } else {
      // 提示失败信息
      sheep.$helper.toast(result.msg || '保存失败，请重试');
    }
  } catch (error) {
    sheep.$helper.toast('网络异常，请稍后重试');
    console.error('更新昵称失败:', error);
  }
}

// 显示编辑昵称弹窗，并回显当前用户昵称
function showNicknameDialog() {
  // 将当前用户昵称赋值给输入框
  nicknameInput.value = state.model.nickname || '';
  // 显示弹窗
  showNicknamePopup.value = true;
}

// 处理退出登录
async function handleLogout() {
  try {
    // 弹出确认对话框
    uni.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      showCancel: true,
      confirmText: '确定',
      cancelText: '取消',
      success: async (res) => {
        if (res.confirm) {
          // 清除用户信息
          sheep.$store("user").logout();
          // 跳转到登录页面或首页
          setTimeout(() => {
            // 根据项目需求决定跳转到哪个页面
            sheep.$router.go('/pages/index/index');
          }, 1500);
        }
      }
    });

  } catch (error) {
    console.error('退出登录失败:', error);
    sheep.$helper.toast('退出登录失败，请重试');
  }
}
</script>

<style>
.user-info-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 200rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.back-button,
.nav-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #000;
}

/* 个人资料列表 */
.info-list {
  background-color: #fff;
  margin-top: 20rpx;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 110rpx;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 32rpx;
  color: #333;
}

.info-value {
  font-size: 32rpx;
  color: #666;
}

.info-value-with-arrow {
  display: flex;
  align-items: center;
}

.info-value-with-arrow text {
  font-size: 32rpx;
  color: #666;
  margin-right: 20rpx;
}

.placeholder {
  color: #999;
}

/* 头像样式 */
.avatar-container {
  display: flex;
  align-items: center;
}

.avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

/* 底部保存按钮 */
.footer {
  padding: 40rpx 30rpx;
}

.save-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #f04438;
  color: #fff;
  border-radius: 45rpx;
  font-size: 32rpx;
}

/* 编辑昵称弹窗样式 */
.nickname-popup-content {
  width: 85%;
  max-width: 500rpx;
  background-color: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.15);
  animation: popupShow 0.3s ease-out;
}

@keyframes popupShow {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.close-icon {
  color: #999;
  transition: color 0.2s;
}

.close-icon:active {
  color: #666;
  transform: scale(0.9);
}

.input-container {
  padding: 30rpx;
  position: relative;
}

.nickname-input {
  width: 100%;
  height: 100rpx;
  font-size: 34rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  transition: all 0.2s;
  background-color: #fafafa;
}

.nickname-input:focus {
  border-color: #007aff;
  background-color: #ffffff;
  box-shadow: 0 0 0 4rpx rgba(0, 122, 255, 0.1);
  outline: none;
}

.char-count {
  position: absolute;
  right: 40rpx;
  bottom: 10rpx;
  font-size: 24rpx;
  color: #999;
}

.save-nickname-button {
  width: 80%;
  margin: 20rpx auto 40rpx;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 45rpx;
  font-size: 32rpx;
  font-weight: 500;
  transition: all 0.2s;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
}

.save-nickname-button:active {
  background-color: #0062cc;
  box-shadow: 0 2rpx 6rpx rgba(0, 122, 255, 0.2);
  transform: translateY(2rpx);
}

.save-nickname-button:disabled {
  background-color: #cccccc;
  box-shadow: none;
  transform: none;
}

/* 底部退出登录按钮 */
.footer {
  padding: 40rpx 30rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #f5f5f5;
}

.logout-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #fff;
  color: #333;
  border: 1rpx solid #e0e0e0;
  border-radius: 45rpx;
  font-size: 32rpx;
}
</style>
